package com.stockz.ui.swing.charting.widget;

import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import com.stockz.ui.swing.charting.util.RepaintStockChartPanelUtil;
import com.stockz.ui.swing.charting.util.SetStockChartPanelSizeUtil;
import com.stockz.ui.swing.charting.view.StockChartPanel;
import com.stockz.ui.swing.charting.view.StockChartPanelState;
import com.stockz.ui.swing.charting.view.StockChartPanelStructure;
import com.stockz.ui.swing.widget.JButton;

public class ZoomOutButton extends JButton implements ActionListener {
	private static final long serialVersionUID = 6148804316116338138L;
	
	private final StockChartPanel stockChartPanel;
	
	public ZoomOutButton(StockChartPanel stockChartPanel) {
		super("Zoom Out","zoom_out.png");
		this.stockChartPanel = stockChartPanel;
		addActionListener(this);
		Toolkit.getDefaultToolkit().addAWTEventListener( new AWTEventListener(){
		    public void eventDispatched(AWTEvent e){
		    	if(e instanceof KeyEvent){
		    		KeyEvent keyEvent = (KeyEvent)e;
			       if(!keyEvent.isConsumed() && keyEvent.getID() == KeyEvent.KEY_RELEASED 
			    		   &&  keyEvent.getKeyCode() == KeyEvent.VK_DOWN && keyEvent.isControlDown()){
			    	   keyEvent.consume();
			    	   actionPerformed(null);
			       }
		    	}
		    }
		}, AWTEvent.KEY_EVENT_MASK);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if(stockChartPanel != null){
			StockChartPanelState state = stockChartPanel.getStockChartPanelState();
			StockChartPanelStructure structure = stockChartPanel.getStockChartPanelStructure();
			int current = state.getTimeUnitSpace();
			int increment = structure.getZoomIncrement();
			if(current - increment >= 0 ){
				state.setTimeUnitSpace(current-increment);
				SetStockChartPanelSizeUtil.setStockChartPanelSize(stockChartPanel);
				RepaintStockChartPanelUtil.repaintStockChartPanel(stockChartPanel);
			}
		}
	}
}
